<template>
  <div class="writingManagement">
    <div class="topBar">
      <div class="searchBar">
        <el-form
          ref="queryForm"
          size="small"
          label-width="68px"
          :inline="true"
          :model="queryParams">
          <el-form-item label="发明名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入发明名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="专利类型" prop="patentType">
            <el-select v-model="queryParams.patentType" placeholder="请选择专利类型" clearable>
              <el-option
                v-for="dict in dict.type.patent_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="专利领域" prop="patentField">
            <el-select v-model="queryParams.patentField" placeholder="请选择专利类型" clearable>
              <el-option
                v-for="dict in dict.type.patent_field"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="状态" prop="state">-->
<!--            <el-select v-model="queryParams.state" placeholder="请选择状态" clearable>-->
<!--              <el-option-->
<!--                v-for="dict in dict.type.state"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="operateBar">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:task:add']"
        >新增</el-button>
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:task:remove']"
        >删除</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:task:export']"
        >导出</el-button>
      </div>
    </div>
    <el-table
      stripe
      height="100%"
      style="width: 100%"
      :data="taskList"
      v-loading="loading"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="下单金额" prop="amount" width="80" />
      <el-table-column
        width="300"
        label="发明名称"
        prop="name"
        show-overflow-tooltip />
      <el-table-column label="专利类型" prop="patentType" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.patent_type" :value="scope.row.patentType"/>
        </template>
      </el-table-column>
      <el-table-column label="专利领域" prop="patentField" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.patent_field" :value="scope.row.patentField"/>
        </template>
      </el-table-column>
      <el-table-column label="要求时限" prop="requestTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requestTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="撰写要求" prop="writingRequirements" show-overflow-tooltip />
      <el-table-column label="联系人" prop="contacts" width="80" />
      <el-table-column label="联系人手机号" prop="contactsPhone" width="120" />
      <el-table-column label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column label="状态" prop="state" width="70">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="代理师" prop="rickNikeName" width="120"></el-table-column>
      <el-table-column label="发布人" prop="nikeName" width="80" />
      <el-table-column label="操作" width="260">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-assign"
            @click="handleAssign(scope.row)"
            v-hasPermi="['system:task:assign']"
          >指派任务</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-assign"
            @click="handleComplete(scope.row)"
            v-hasPermi="['system:task:complete']"
          >完成任务</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
      :before-close="closeEvent">
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下单金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入下单金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="要求时限" prop="requestTime">
              <el-date-picker
                style="width: 100%;"
                clearable
                v-model="form.requestTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择要求时限">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专利类型" prop="patentType">
              <el-select
                style="width: 100%;"
                v-model="form.patentType"
                placeholder="请选择专利类型">
                <el-option
                  v-for="dict in dict.type.patent_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专利领域" prop="patentField">
              <el-select
                style="width: 100%;"
                v-model="form.patentField"
                placeholder="请输入专利领域">
                <el-option
                  v-for="dict in dict.type.patent_field"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人手机号" prop="contactsPhone">
              <el-input v-model="form.contactsPhone" placeholder="请输入联系人手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接单人" prop="rickUserId">
              <el-input  v-model="form.rickUserId" placeholder="请输入接单人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发布人" prop="nikeName">
              <el-input  v-model="form.nikeName" placeholder="请输入发布人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select
                style="width: 100%;"
                v-model="form.state"
                placeholder="请选择状态">
                <el-option
                  v-for="dict in dict.type.state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传文件" prop="files">
              <el-upload
                :action="uploadUrl"
                :headers="headerObj"
                multiple
                :limit="3"
                :file-list="fileList"
                :on-success="handleAvatarSuccess_"
                :before-upload="beforeAvatarUpload">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="发明名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入发明名称" />
        </el-form-item>
        <el-form-item label="撰写要求" prop="writingRequirements">
          <el-input v-model="form.writingRequirements" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEvent">确 定</el-button>
        <el-button @click="closeEvent">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="完成任务"
      :visible.sync="finishTaskVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="finishTaskCancel"
      append-to-body>
      <el-form ref="finishTaskForm" :model="finishTaskForm" :rules="finishTaskRules" label-width="80px">
        <el-form-item label="上传文件" prop="fileList">
          <el-upload
            :action="uploadUrl"
            :headers="headerObj"
            multiple
            :limit="3"
            :file-list="fileList"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">上传文件大小不得超过 20MB!</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="finishTaskSubmit">确 定</el-button>
        <el-button @click="finishTaskCancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="指派任务"
      :visible.sync="assignTaskVisible"
      width="500px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body>
      <el-form
        ref="assignTaskForm"
        :model="assignTaskForm"
        :rules="assignTaskRules"
        label-width="80px">
        <el-form-item label="代理师" prop="rickUserId">
          <el-select style="width: 100%" v-model="assignTaskForm.rickUserId" placeholder="请输入代理师">
            <el-option
              v-for="dict in businessPerson"
              :key="dict.userId"
              :label="dict.nickName"
              :value="dict.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="assignTaskSubmit">确 定</el-button>
        <el-button @click="assignTaskVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, assignTask, completeTask, listBusiness } from '@/api/writingManagement'
import {getToken} from '@/utils/auth'
export default {
  name: "Task",
  dicts: ['patent_type', 'case_type', 'case_status', 'filing_type', 'patent_field', 'state'],
  data() {
    return {
      // 查询参数
      queryParams: {
        name: null,
        patentType: null,
        patentField: null,
        state: null,
        pageNum: 1,
        pageSize: 10,
      },

      taskList: [],
      total: 0,
      loading: true,
      ids: [],
      multiple: true,

      title: "",
      open: false,
      form: {
        id: null,

        amount: null,
        requestTime: null,
        patentType: null,
        patentField: null,
        contacts: null,
        contactsPhone: null,
        rickUserId: null,
        nikeName: null,
        state: null,
        files: null,
        name: null,
        writingRequirements: null,
        remark: null,
      },
      rules: {
        amount: [
          { required: true, message: "下单金额不能为空", trigger: "blur" }
        ],
        requestTime: [
          { required: true, message: "要求时限为空", trigger: "blur" }
        ],
        rickUserId: [
          { required: true, message: "接单人不能为空", trigger: "blur" }
        ],
      },

      //完成任务相关
      uploadUrl: "http://47.120.71.81/prod-api/common/uploadFileOss",
      headerObj: { Authorization: getToken() },
      fileList: [],
      finishTaskVisible: false,
      finishTaskForm: {
        id: "",
        fileList: []
      },
      finishTaskRules: {
        fileList: [
          { required: true, trigger: "change", message: "请选择要上传的文件" }
        ],
      },

      //指派任务相关
      businessPerson: [],
      assignTaskVisible: false,
      assignTaskForm: {
        id: "",
        rickUserId: "",
      },
      assignTaskRules: {
        rickUserId: [
          { required: true, trigger: "change", message: "请选择代理师" }
        ],
      },
    };
  },
  created() {
    this.getBusinessPerson()
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    //删除
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除任务编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //导出
    handleExport() {
      this.download('system/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    // 取消按钮
    closeEvent() {
      this.$refs['form'].resetFields();
      this.open = false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务";
      });
    },
    handleAvatarSuccess_(res, file) {
      const {msg, code} = res;
      this.form.files.push({url: msg});
    },
    /** 提交按钮 */
    submitEvent() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.closeEvent()
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.closeEvent()
              this.getList();
            });
          }
        }
      });
    },
    //完成任务相关
    beforeAvatarUpload(file) {
      const isLt20M = file.size / 1024 / 1024 < 20;
      if (!isLt20M) {
        this.$message.error('上传文件大小不得超过 20MB!');
      }
      return isLt20M;
    },
    handleAvatarSuccess(res, file) {
      const {msg, code} = res;
      this.finishTaskForm.fileList.push({url: msg});
    },
    handleComplete(row) {
      const {id} = row;
      this.finishTaskForm = { id, fileList: [] }
      this.finishTaskVisible = true;
      this.$nextTick(() => {
        this.$refs["finishTaskForm"].resetFields();
      })
    },
    finishTaskCancel() {
      this.fileList = [];
      this.finishTaskVisible = false;
    },
    finishTaskSubmit() {
      this.$refs["finishTaskForm"].validate(valid => {
        if (valid) {
          completeTask(this.finishTaskForm).then(response => {
            this.$modal.msgSuccess("操作成功");
            this.finishTaskCancel();
            this.getList();
          })
        }
      });
    },
    //指派任务相关
    getBusinessPerson() {
      const params = {
        pageNum: 1,
        pageSize: 100
      }
      listBusiness(params).then(res => {
        const {rows = []} = res;
        this.businessPerson = rows;
      })
    },
    handleAssign(row) {
      const {id} = row;
      this.assignTaskForm = { id, rickUserId: "" }
      this.assignTaskVisible = true;
      this.$nextTick(() => {
        this.$refs["assignTaskForm"].resetFields()
      })
    },
    assignTaskSubmit() {
      this.$refs["assignTaskForm"].validate(valid => {
        if (valid) {
          assignTask(this.assignTaskForm).then(response => {
            this.$modal.msgSuccess("指派成功");
            this.assignTaskVisible = false;
            this.getList();
          });
        }
      });
    },
  }
};
</script>
<style lang="scss" scoped>
div.writingManagement {
  div.topBar {
    height: 36px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    div.searchBar {
      .el-form-item {
        margin-bottom: 0;
      }
    }
  }
}
</style>
